package com.atwj.controller;


import com.atwj.Service.BookService;
import com.atwj.Service.impl.BookServiceImpl;
import com.atwj.entity.Book;
import com.atwj.entity.Page;
import com.atwj.utils.webUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 吴先森
 * @description: 处理首页查询书籍的信息操作
 * @create 2022-03-27 14:07
 */
public class ClientBookServlet extends BaseServlet {
    private BookService bookService = new BookServiceImpl();

    /**
     * //前台--->处理首页页面中数据的分页操作
     *
     * @param req
     * @param resp
     * @author 吴先森
     * @date 2022/3/27 14:11
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数 pageNo和pageSize
        int pageNo = webUtil.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = webUtil.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用BookService.page(pageNo, pageSize) Page对象
        Page<Book> page = bookService.page(pageNo, pageSize);

        page.setUrl("client/clientBookServlet?action=page");

        //保存page对象到request域
        req.setAttribute("page", page);
        //请求转发到/pages/client/index.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
    }

    /**
     * 根据价格区间求数据
     *
     * @param req
     * @param resp
     * @author 吴先森
     * @date 2022/3/27 15:28
     */
    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数 pageNo和pageSize
        int pageNo = webUtil.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = webUtil.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min = webUtil.parseInt(req.getParameter("min"), 0);
        int max = webUtil.parseInt(req.getParameter("max"), Integer.MAX_VALUE);

        //调用BookService.page(pageNo, pageSize) Page对象
        Page<Book> page = bookService.pageByPrice(pageNo, pageSize, min, max);

        //解决分页条中进行价格区间查询后，点击页码时返回初始页面的bug
        StringBuilder sb = new StringBuilder("client/clientBookServlet?action=pageByPrice");
        if (req.getParameter("min") != null) {
            sb.append("&min=").append(req.getParameter("min"));
        }
        if (req.getParameter("max") != null) {
            sb.append("&max=").append(req.getParameter("max"));
        }
        page.setUrl(sb.toString());


        //保存page对象到request域
        req.setAttribute("page", page);
        //请求转发到/pages/client/index.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req, resp);
    }
}
